package com.project_test.kun.travelling_1st.HomePage;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioAttributes;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.project_test.kun.travelling_1st.Butler.ButlerActivity;
import com.project_test.kun.travelling_1st.HomePage.Util.URL;
import com.project_test.kun.travelling_1st.HomePage.View.GView;
import com.project_test.kun.travelling_1st.HomePage.activities.HomePageCarActivity;
import com.project_test.kun.travelling_1st.HomePage.activities.HomePageHouseActivity;
import com.project_test.kun.travelling_1st.HomePage.adapter.HomePAdapter;
import com.project_test.kun.travelling_1st.HomePage.adapter.HomePHeadGridAdapter;
import com.project_test.kun.travelling_1st.HomePage.adapter.HomePHeadPagerAdapter;
import com.project_test.kun.travelling_1st.HomePage.category.HomePListItemBanner;
import com.project_test.kun.travelling_1st.HomePage.category.HomePListItemButton;
import com.project_test.kun.travelling_1st.HomePage.category.HomePListItemIndex;
import com.project_test.kun.travelling_1st.R;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomePageFragment extends Fragment implements Runnable, ViewPager.OnPageChangeListener, View.OnTouchListener {


    private RequestQueue mRequestQueue;
    private List<HomePListItemBanner> mHomePListItemBanners;//Viewpager中的数据
    private List<HomePListItemButton> mHomePListItemButtons;//Button中的数据
    private List<HomePListItemIndex> mHomePListItemIndices;//Item中的数据
    private PullToRefreshListView mListView;
    private HomePAdapter mAdapter;
    private HomePHeadGridAdapter mGridAdapter;
    private ViewPager mViewPager;
    private HomePHeadPagerAdapter mPagerAdapter;
    private LinearLayout mPotinLinear;
    private Bitmap mNullBitmap;
    private Bitmap mRadBitmap;
    private ArrayList<ImageView> mImageList;
    private ConnectivityManager mCwjManager;   //获得是否联网服务
    private int time;
    private GView mGridView;


    public HomePageFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //获得请求列表
        mRequestQueue = Volley.newRequestQueue(getContext());
        //初始化数据类
        mHomePListItemBanners = new ArrayList<>();
        mHomePListItemButtons = new ArrayList<>();
        mHomePListItemIndices = new ArrayList<>();

        mImageList = new ArrayList<>();

        mNullBitmap = twoCollect(R.drawable.ease_unread_nul, 20, 20);//白点

        mRadBitmap = twoCollect(R.drawable.ease_unread_dot, 20, 20); //红点
        time = 0;


    }

    private Bitmap twoCollect(int id, int height, int width) {
        //图片的二次采样
        //1.第一次采样,并不返回bitmap,仅仅返回原始图片宽高
        BitmapFactory.Options options = new BitmapFactory.Options();//配置类
        options.inJustDecodeBounds = true;//只得到原始的尺寸,并不得到图片具体像素
        Bitmap bitmapFirst = BitmapFactory.decodeResource(getResources(), id, options);//此时的bitamp是空的

        //获取原始图片的宽高
        int srcHeight = options.outHeight;
        int srcWidth = options.outWidth;
//              设计需求,如:宽50,高80;

        //2.第二次采样
        options.inJustDecodeBounds = false;//获得原有像素
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        int samleSize = 1;
        while (srcWidth / samleSize > width | srcHeight / samleSize > height) {
            samleSize *= 2;
        }
        options.inSampleSize = samleSize;
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), id, options);
        return bitmap;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        mCwjManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        View view = inflater.inflate(R.layout.fragment_home_page, container, false);
        initView(view);//初始化控件
        initData();//获得数据

        return view;
    }

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 999) {//无网络
                mListView.onRefreshComplete();//没有网络直接关闭下拉刷新
                Toast.makeText(getContext(), "当前无网络,请查看设置!", Toast.LENGTH_SHORT).show();

            }
            if (msg.what == 0) {
                mListView.onRefreshComplete();//关闭下拉刷新
                //对potinLinear添加子控件
                mPotinLinear.removeAllViews();
                LinearAddChild();
            }
            if (msg.what == 1) {
                mHomePListItemBanners.clear();
                mHomePListItemButtons.clear();
                mHomePListItemIndices.clear();
                initData();
            }
            if (msg.what == 2) {
                int currentItem = mViewPager.getCurrentItem();
                mViewPager.setCurrentItem(currentItem + 1);

                mHandler.postDelayed(HomePageFragment.this, 4000);
            }
        }
    };

    public void LinearAddChild() {

        for (int i = 0; i < mHomePListItemBanners.size(); i++) {
            ImageView childView = new ImageView(getContext());
            childView.setImageBitmap(mNullBitmap);
            mPotinLinear.addView(childView);
        }
        ((ImageView) mPotinLinear.getChildAt(0)).setImageBitmap(mRadBitmap);
        if (time < 1) {
            time++;
            //对ViewPager进行监听
            mViewPager.addOnPageChangeListener(this);
            mHandler.postDelayed(this, 4000);//自动轮播
            //对ViewPager进行触碰事件监听
            mViewPager.setOnTouchListener(this);
        }
    }

    public void initData() {

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                URL.HOMEPAGER_URL,
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONObject data = response.getJSONObject("data");

                            JSONArray bannerList = data.getJSONArray("bannerList");//Viewpager中的数据
                            for (int i = 0; i < bannerList.length(); i++) {
                                JSONObject bannerListJSONObject = bannerList.getJSONObject(i);
                                HomePListItemBanner banner = new HomePListItemBanner();
                                banner.pashJson(bannerListJSONObject);
                                mHomePListItemBanners.add(banner);
                            }
                            //获得相应的图片广告信息


                            for (int i = 0; i < mHomePListItemBanners.size(); i++) {
                                ImageView image = new ImageView(getContext());
                                HomePListItemBanner banner = mHomePListItemBanners.get(i);
                                Picasso.with(getContext()).load(banner.getImg()).into(image);
                                mImageList.add(image);
                            }
                            mPagerAdapter = new HomePHeadPagerAdapter(mHomePListItemBanners, mImageList,getContext());
                            mViewPager.setAdapter(mPagerAdapter);


                            JSONArray buttonList = data.getJSONArray("buttonList");//Button中的数据
                            for (int i = 0; i < buttonList.length(); i++) {
                                JSONObject buttonListJSONObject = buttonList.getJSONObject(i);
                                HomePListItemButton button = new HomePListItemButton();
                                button.pashJson(buttonListJSONObject);
                                mHomePListItemButtons.add(button);
                            }
                            mGridAdapter.notifyDataSetChanged();
                            JSONArray indexList = data.getJSONArray("indexList");//Item中的数据
                            for (int i = 0; i < indexList.length(); i++) {
                                JSONObject jsonObject = indexList.getJSONObject(i);
                                HomePListItemIndex index = new HomePListItemIndex();
                                index.pashJson(jsonObject);
                                mHomePListItemIndices.add(index);
                            }
                            mAdapter.notifyDataSetChanged();
                            Message msg = mHandler.obtainMessage();
                            msg.what = 0;
                            mHandler.sendMessage(msg);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }
        );
        mRequestQueue.add(jsonObjectRequest);//加入请求
    }

    private void initView(View view) {
        mListView = (PullToRefreshListView) view.findViewById(R.id.homepage_ListView);
//        TextView empty= (TextView) view.findViewById(R.id.empty);
//        mListView.setEmptyView(empty);//添加空视图
        View headerView = View.inflate(getContext(), R.layout.head_fragment_home_list, null);
        //获得头布局 的控件
        initHeadView(headerView);
        ListView refreshableView = mListView.getRefreshableView();
//        mListView.addView(headerView);
        refreshableView.addHeaderView(headerView);
//        mListView.onRefreshComplete();//关闭下拉刷新
        //添加adapter
        mAdapter = new HomePAdapter(getContext(), mHomePListItemIndices);
        mListView.setAdapter(mAdapter);
        pashUpData();//下拉刷新
    }

    private void initHeadView(View headerView) {
        //获得自定义GridView
        mGridView = (GView) headerView.findViewById(R.id.grid_head_list_home);
        mViewPager = (ViewPager) headerView.findViewById(R.id.viewPager_head_list_home);
        mGridAdapter = new HomePHeadGridAdapter(getContext(), mHomePListItemButtons);
        mPotinLinear = (LinearLayout) headerView.findViewById(R.id.linear_point_head_list_honme);
        mGridView.setAdapter(mGridAdapter);

        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                Intent intent = null;
                switch (i) {
                    case 0:
                        Intent intent3=new Intent(getContext(), HomePageHouseActivity.class);
                        getContext().startActivity(intent3);
                        break;
                    case 1:
                        Intent intent=new Intent(getContext(), HomePageCarActivity.class);
                        getContext().startActivity(intent);
                        break;
                    case 2:
                        Intent intent2=new Intent(getContext(), ButlerActivity.class);
                        getContext().startActivity(intent2);
                        break;
                    case 3:
                        break;
                    case 4:
                        break;
                    case 5:
                        break;
                }
            }
        });


    }

    //    下拉刷新
    private void pashUpData() {
        mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {

            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                NetworkInfo info = mCwjManager.getActiveNetworkInfo();
                if (info == null || !mCwjManager.getBackgroundDataSetting()) {
                    Message msg = mHandler.obtainMessage();
                    msg.what = 999;
                    mHandler.sendMessage(msg);
                } else {
                    Message msg = mHandler.obtainMessage();
                    msg.what = 1;
                    mHandler.sendMessage(msg);
                }
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

            }
        });
    }


    @Override
    public void run() {
        Message msg = mHandler.obtainMessage();
        msg.what = 2;
        mHandler.sendMessage(msg);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        for (int i = 0; i < mPotinLinear.getChildCount(); i++) {
            ((ImageView) mPotinLinear.getChildAt(i)).setImageBitmap(mNullBitmap);
        }
        position = position % mPotinLinear.getChildCount();
        ImageView child = (ImageView) mPotinLinear.getChildAt(position);
        child.setImageBitmap(mRadBitmap);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mHandler.removeCallbacks(HomePageFragment.this);
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        return false;
    }
}
